package com.weacar.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.JavascriptInterface;
import android.webkit.JsPromptResult;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.apkfuns.logutils.LogUtils;
import com.example.zhouwei.library.CustomPopWindow;
import com.google.gson.Gson;
import com.kongzue.dialog.interfaces.OnDialogButtonClickListener;
import com.kongzue.dialog.util.BaseDialog;
import com.kongzue.dialog.v3.MessageDialog;
import com.weacar.R;
import com.weacar.bean.BaseBean;
import com.weacar.config.Constans;
import com.weacar.utils.AppManager;
import com.weacar.utils.DesUtil;
import com.weacar.utils.NetWorkUtil;
import com.weacar.utils.PriceUtil;
import com.weacar.utils.SystemUtil;
import com.weacar.utils.TimeUtil;
import com.weacar.utils.ToastUtil;

import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.math.BigDecimal;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 汽车详情页可拍卖
 */
public class CarDetailActivity extends BaseActivity {

    protected static final String APP_CACHE_DIRNAME = "/cache_path";

    @BindView(R.id.rl_main)
    RelativeLayout rl_main;
    @BindView(R.id.tv_show_my_price)
    TextView tv_show_my_price;
    @BindView(R.id.wb_main)
    WebView wb_main;


    private String web_url;
    private int car_id;
    private String token;
    // 1.竞拍 2.秒杀
    private int auction_type;
    // 秒杀价
    private String online_price;
    // 是否是搜索页面跳转过来的
    private boolean isSearch = false;


    @OnClick({R.id.iv_back, R.id.tv_show_my_price})
    public void click(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.tv_show_my_price:
                if (auction_type == 1) {
                    showPricePop();
                } else if (auction_type == 2) {
                    String format_online_price;
                    if (online_price.contains(".")) {
                        format_online_price = online_price.substring(0, online_price.indexOf("."));
                    } else {
                        format_online_price = online_price;
                    }
                    String format_price = PriceUtil.getCommaFormat(BigDecimal.valueOf(Integer.parseInt(format_online_price)));
                    MessageDialog.show(CarDetailActivity.this, "提示:一口价", "您的一口价是:" + format_price + "元" + "(" + PriceUtil.digitUppercase(Integer.parseInt(format_online_price)) + ")", "确定出价", "取消").setOnOkButtonClickListener(new OnDialogButtonClickListener() {
                        @Override
                        public boolean onClick(BaseDialog baseDialog, View v) {
                            // 一口价到服务器
                            killPriceToServer();
                            return false;
                        }
                    });
                }
                break;
        }
    }


    public void showPricePop() {
        Resources resources = getApplication().getResources();

        DisplayMetrics displayMetrics = resources.getDisplayMetrics();

        int widthPixels = (int) (displayMetrics.widthPixels * 0.8);//当前屏幕宽

        int heightPixels = (int) (displayMetrics.heightPixels * 0.5);//当前屏幕高


        View contentView = LayoutInflater.from(this).inflate(R.layout.pop_show_my_price, null);
        TextView tv_cancel = contentView.findViewById(R.id.tv_cancel);
        TextView tv_confirm = contentView.findViewById(R.id.tv_confirm);
        final TextView tv_ob_price = contentView.findViewById(R.id.tv_ob_price);
        final EditText et_price = contentView.findViewById(R.id.et_price);
        ImageView iv_clean = contentView.findViewById(R.id.iv_clean);

        // 监听用户输入
        et_price.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {

                if (editable.toString().equals("")) {
                    tv_ob_price.setText("");
                } else {
                    double d = Double.parseDouble(editable.toString());
                    tv_ob_price.setText(PriceUtil.digitUppercase(d));
                }

            }
        });


        final CustomPopWindow customPopWindow = new CustomPopWindow.PopupWindowBuilder(this)
                .setView(contentView)
                .enableBackgroundDark(true) //弹出popWindow时，背景是否变暗
                .setBgDarkAlpha(0.7f) // 控制亮度
                .size(widthPixels, heightPixels)//显示大小
                .create()
                .showAtLocation(rl_main, Gravity.CENTER, 0, 0);

        tv_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                customPopWindow.dissmiss();
            }
        });

        tv_confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (et_price.getText().toString().equals("")) {
                    ToastUtil.showShort(getApplicationContext(), "请输入正确格式的价格");
                    return;
                }

                final int price = Integer.parseInt(et_price.getText().toString());

                if (price == 0) {
                    ToastUtil.showShort(getApplicationContext(), "请输入正确格式的价格");
                    return;
                }

                if (price % 100 == 0) {
                    String format_price = PriceUtil.getCommaFormat(BigDecimal.valueOf(price));
                    MessageDialog.show(CarDetailActivity.this, "提示:竞拍后价格不能取消", "您输入的价格是:" + format_price + "元" + "(" + PriceUtil.digitUppercase(price) + ")", "确定出价", "取消").setOnOkButtonClickListener(new OnDialogButtonClickListener() {
                        @Override
                        public boolean onClick(BaseDialog baseDialog, View v) {
                            // Toast.makeText(getApplicationContext(), "恭喜出价成功.", Toast.LENGTH_SHORT).show();
                            // 提交出价到服务器
                            commitPriceToServer(price);
                            return false;
                        }
                    });
                    customPopWindow.dissmiss();
                } else {
                    ToastUtil.showShort(getApplicationContext(), "请输入正确格式的价格");
                }
            }
        });
        iv_clean.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                et_price.setText("");
            }
        });
    }

    /**
     * 提交竞拍价格
     */
    public void commitPriceToServer(final int price) {
        if (!NetWorkUtil.isNetworkAvailable(this)) {
            ToastUtil.showShort(getApplicationContext(), "当前网络不可用");
            return;
        }

        try {
            showLoading("提交出价到服务器中...");
            RequestParams params = new RequestParams(Constans.URL_HEADER + Constans.commit_price);
            params.setCacheMaxAge(0);
            JSONObject js_request = new JSONObject();
            js_request.put("token", token);
            js_request.put("id", car_id);
            js_request.put("price", price);
            params.setAsJsonContent(true);
            params.setBodyContent(DesUtil.encrypt(js_request.toString()));
//            LogUtils.d("commit_price_url =  " + params.getUri());
//            LogUtils.d("commit_price_url_params = " + params.getBodyContent());
            x.http().post(params, new Callback.CommonCallback<String>() {
                @Override
                public void onSuccess(String result) {
                    closeLoading();
                    LogUtils.d("result = " + result);
                    Gson gson = new Gson();
                    BaseBean baseBean = gson.fromJson(result, BaseBean.class);
                    if (baseBean != null) {
                        try {
                            com.alibaba.fastjson.JSONObject jsonObject = com.alibaba.fastjson.JSONObject.parseObject(DesUtil.decrypt(baseBean.getData()));
                            String msg = jsonObject.get("msg").toString();
                            if (msg.equals("出价成功")) {
                                tv_show_my_price.setText("修改出价(已出" + PriceUtil.getPriceByWan(price) + "万元)");
                            }
                            ToastUtil.showShort(getApplicationContext(), msg);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }

                @Override
                public void onError(Throwable ex, boolean isOnCallback) {
                    closeLoading();
                }

                @Override
                public void onCancelled(CancelledException cex) {
                    closeLoading();
                }

                @Override
                public void onFinished() {
                    closeLoading();
                }
            });

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 秒杀一口价
     */
    public void killPriceToServer() {
        if (!NetWorkUtil.isNetworkAvailable(this)) {
            ToastUtil.showShort(getApplicationContext(), "当前网络不可用");
            return;
        }
        try {
            showLoading("一口价提交到服务器中...");
            RequestParams params = new RequestParams(Constans.URL_HEADER + Constans.kill_price);
            params.setCacheMaxAge(0);
            JSONObject js_request = new JSONObject();
            js_request.put("token", token);
            js_request.put("id", car_id);
            params.setAsJsonContent(true);
//            LogUtils.d("url = " + params.getUri());
//            LogUtils.d("params = " + params.getBodyParams());
            params.setBodyContent(DesUtil.encrypt(js_request.toString()));
            x.http().post(params, new Callback.CommonCallback<String>() {
                @Override
                public void onSuccess(String result) {
                    closeLoading();
                    LogUtils.d("result = " + result);
                    Gson gson = new Gson();
                    BaseBean baseBean = gson.fromJson(result, BaseBean.class);
                    if (baseBean != null) {
                        try {
                            com.alibaba.fastjson.JSONObject jsonObject = com.alibaba.fastjson.JSONObject.parseObject(DesUtil.decrypt(baseBean.getData()));
                            String msg = jsonObject.get("msg").toString();
                            ToastUtil.showShort(getApplicationContext(), msg);
                            if (msg.equals("秒杀成功")) {
                                if (isSearch) {
                                    Intent intent = new Intent(getApplicationContext(), MainActivity.class);
                                    intent.putExtra("jumpMyPrice", true);
                                    startActivity(intent);
                                    AppManager.getInstance().finishAllActivity();
                                } else {
                                    setResult(3);
                                    finish();
                                }
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }

                @Override
                public void onError(Throwable ex, boolean isOnCallback) {
                    closeLoading();
                }

                @Override
                public void onCancelled(CancelledException cex) {
                    closeLoading();
                }

                @Override
                public void onFinished() {
                    closeLoading();
                }
            });

        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public class JavaScriptinterface {

        private Context mContext;

        /**
         * Instantiate the interface and set the context
         */
        public JavaScriptinterface(Context c) {
            mContext = c;
        }

        @JavascriptInterface
        public void close() {
            finish();
        }
    }

    /**
     * 初始化webview相关
     */
    @SuppressLint("JavascriptInterface")
    public void initWebView() {
        wb_main.getSettings().setJavaScriptEnabled(true);
        wb_main.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
        // 建议缓存策略为，判断是否有网络，有的话，使用LOAD_DEFAULT,无网络时，使用LOAD_CACHE_ELSE_NETWORK
        // wb_main storage API 功能
        // wb_main.getSettings().setDomStorageEnabled(true);
        // 开启database storage API功能
//        wb_main.getSettings().setDatabaseEnabled(true);
//        String cacheDirPath = getFilesDir().getAbsolutePath()
//                + APP_CACHE_DIRNAME;
//        // Log.i(TAG, cacheDirPath);
//        // 设置数据库缓存路径
//        wb_main.getSettings().setDatabasePath(cacheDirPath); // API 19
//        // deprecated
//        // 设置Application caches缓存目录
//        wb_main.getSettings().setAppCachePath(cacheDirPath);
//        // 开启Application Cache功能
//        wb_main.getSettings().setAppCacheEnabled(true);

        // 让JS调用Android的方法
        wb_main.addJavascriptInterface(new JavaScriptinterface(this),
                "android");

        wb_main.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);

            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                LogUtils.d("web_url = " + url);
                view.loadUrl(url);
                return true;
            }
        });

        wb_main.setWebChromeClient(new WebChromeClient() {
            @Override
            public boolean onJsAlert(WebView view, String url, String message,
                                     JsResult result) {
                // TODO Auto-generated method stub
                result.confirm();
                return super.onJsAlert(view, url, message, result);
            }

            @Override
            public boolean onJsPrompt(WebView view, String url, String message,
                                      String defaultValue, JsPromptResult result) {
                // TODO Auto-generated method stub
                return super.onJsPrompt(view, url, message, defaultValue,
                        result);
            }

            // 获取webview的title
            @Override
            public void onReceivedTitle(WebView view, String web_title) {
                super.onReceivedTitle(view, web_title);
                LogUtils.d("web_title = " + web_title);

            }

        });
        wb_main.loadUrl(web_url);
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setStatusBarStyle("1");
        setContentView(R.layout.activity_car_detail);
        AppManager.getInstance().addActivity(this);
        ButterKnife.bind(this);
        web_url = getIntent().getStringExtra("web_url");
        car_id = getIntent().getIntExtra("car_id", 0);
        token = getIntent().getStringExtra("token");
        auction_type = getIntent().getIntExtra("auction_type", 0);
        online_price = getIntent().getStringExtra("online_price");
        isSearch = getIntent().getBooleanExtra("isSearch", false);

        boolean hidden = getIntent().getBooleanExtra("hidden", false);
        if (hidden) {
            tv_show_my_price.setVisibility(View.GONE);
        }


        if (auction_type == 2) {
            tv_show_my_price.setText("我要秒杀");
        }
//        LogUtils.d("car_id = " + car_id);
//        LogUtils.d("token = " + token);
        if (web_url != null && !web_url.equals("")) {
            initWebView();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (wb_main != null) {
            wb_main.loadDataWithBaseURL(null, "", "text/html", "utf-8", null);
            wb_main.clearHistory();
            ((ViewGroup)
                    wb_main.getParent()).removeView(wb_main);
            wb_main.destroy();
            wb_main = null;
        }
    }
}
